/*
* @description 本地缓存操作
*/

import { loger } from '@daelui/dogjs/dist/components'
import config from '@/common/config.js'
import storeFile from '@/components/libs/store/store-file.js'
import storeUni from '@/components/libs/store/store-uni.js'
import { querySystemConfigData, queryAppRoutes } from '@/api/system/app.js'

// 缓存器
const store = storeUni
// 缓存key
const keys = {
  systemConfig: 'systemConfig',
	baseUrl: 'baseUrl',
	initFlag: 'initFlag'
}

const storeSer = {
  // 初始化缓存数据
  initStorageData () {
    // 查询系统配置
    return querySystemConfigData().then(res => {
      let data = res.data
      data = Array.isArray(data) ? data : []
      store.setItem(keys.systemConfig, data)
			return res
    })
  },
  // 获取系统配置
  getSystemConfig () {
    return Promise.resolve(store.getItem(keys.systemConfig)).then(list => {
      list = Array.isArray(list) ? list : []
      return list
    })
  },
  // 获取系统配置项
  getSystemConfigItem (key) {
    return Promise.resolve(store.getItem(keys.systemConfig)).then(list => {
      list = Array.isArray(list) ? list : []
      let node = list.find(item => String(item.configKey) === String(key))
      return node || {}
    }).catch(e => loger.error(e))
  },
  // GPS采集间隔时间
  getGpsIntervalTime () {
    return this.getSystemConfigItem('gps_interval_time')
  },
  // GPS采集间隔距离
  getGpsIntervalDistance () {
    return this.getSystemConfigItem('gps_interval_distance')
  },
  // GPS采集间隔时间
  getGpsIntervalTimeValue () {
    return this.getGpsIntervalTime().then(node => {
			return node.configValue
		})
  },
  // GPS采集间隔距离
  getGpsIntervalDistanceValue () {
    return this.getGpsIntervalDistance().then(node => {
			return node.configValue
		})
  },
  // 图片压缩最小值
  getImgMinSize () {
    return this.getSystemConfigItem('img_min_size')
  },
  // 图片压缩缩放最大宽度
  getImgMaxWidth () {
    return this.getSystemConfigItem('img_max_width')
  },
  // 图片压缩缩放最大高度
  getImgMaxHeight () {
    return this.getSystemConfigItem('img_max_height')
  },
	// 获取初始化标识
	getInitFlag () {
		return store.getItem(keys.initFlag)
	},
	// 设置初始化标识
	setInitFlag (value) {
		return store.setItem(keys.initFlag, value)
	},
	// 获取服务主机地址
	getBaseUrl () {
		return store.getItem(keys.baseUrl)
	},
	// 设置服务主机地址
	setBaseUrl (value) {
		return store.setItem(keys.baseUrl, value)
	},
	// 查询应用菜单
	queryAppRoutes ({ vm, isQuery } = {}) {
		let isOnLine =  vm.isOnline()
		let user =  vm.getCurrentUser()
		if (isOnLine && isQuery !== false) {
			return queryAppRoutes().then(res => {
        if (res && String(res.code === '200') && res.data) {
          store.setItem('routes-' + user.userId, res)
        }
				return res
			})
		} else {
			return Promise.resolve(store.getItem('routes-' + user.userId))
		}
	}
}

// 初始化配置
Promise.resolve(storeSer.getBaseUrl()).then(function(value){
  if (/https?:\/\//.test(value)) {
		config.baseUrl = value
	}
})

export default storeSer

export {
  store, keys
}
